<template>
  <el-container class="template-layout">
    <!-- 顶部布局 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
        :searchOptions="searchOptions"
        @resetFields="resetFields"
        @getSearchData="getSearchData"
      ></zz-Search>
    </el-header>
    <!-- 内容区 -->
    <el-main>
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="createBySql" :loading="btnLoading"
            >创建</el-button
          >
          <el-button @click="importByDB" :loading="btnLoading">导入</el-button>
          <el-button @click="batchGenCode" :loading="btnLoading"
            >生成</el-button
          >
          <el-button type="danger" @click="batchDelete" :loading="btnLoading"
            >删除</el-button
          >
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{
                  $t("table.mini")
                }}</el-dropdown-item>
                <el-dropdown-item command="small">{{
                  $t("table.small")
                }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{
                  $t("table.medium")
                }}</el-dropdown-item>
                <el-dropdown-item command="large">{{
                  $t("table.large")
                }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            :icon="'Search'"
            circle
            @click="showSearchHeader = !showSearchHeader"
          />
          <el-button
            :icon="'Operation'"
            circle
            @click="showColumnSetting = true"
          />
        </template>
      </zz-PageBar>
      <el-alert type="warning" :closable="false"
        >在执行某项操作前，请选择业务系统！</el-alert
      >
      <zz-Table
        ref="zzTableRef"
        :data="tableData"
        :hasPage="true"
        :size="tabelSize"
        :page="tablePage"
        :loading="loading"
        :key="tableKey"
        @pageChange="pageChange"
      >
        <vxe-column
          type="checkbox"
          title=""
          fixed="left"
          width="40"
        ></vxe-column>
        <vxe-column
          type="seq"
          title="序号"
          fixed="left"
          width="50"
        ></vxe-column>

        <!-- 动态生成列，根据tableColumns的顺序 -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :min-width="200"
          >
            <template #default="{ row }">
              <!-- 表名称字段特殊处理，显示为链接 -->
              <template v-if="column.field === 'tableName'">
                <a @click="toEdit(row)">{{ row[column.field] }}</a>
              </template>
              <!-- 日期格式需要转换 -->
              <template
                v-else-if="
                  column.field === 'createDate' || column.field === 'updateDate'
                "
              >
                {{ $TOOL.format.formatDateTime(row[column.field]) }}
              </template>
              <!-- 其他字段正常显示 -->
              <template v-else>
                {{ row[column.field] }}
              </template>
            </template>
          </vxe-column>
        </template>

        <vxe-column title="操作" width="300" fixed="right" align="center">
          <template v-slot="{ row }">
            <zz-TableBtn
              :loading="btnLoading"
              @click="formDesign(row)"
              v-if="row.designerType === '1'"
              >表单设计</zz-TableBtn
            >
            <zz-TableBtn :loading="btnLoading" @click="previewCode(row)"
              >预览代码</zz-TableBtn
            >
            <zz-TableBtn :loading="btnLoading" @click="genCode(row)"
              >生成代码</zz-TableBtn
            >
            <zz-TableBtn :loading="btnLoading" @click="synchDb(row)"
              >同步</zz-TableBtn
            >
            <zz-TableBtn
              type="error"
              :loading="btnLoading"
              @click="deleteRow(row)"
              >删除</zz-TableBtn
            >
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>

    <!--引入组件-->
    <zz-ColumnSetting
      v-model="showColumnSetting"
      :columns="tableColumns"
      :default-columns="defaultTableColumns"
      :storage-key="tableColumnName"
      list-id="code-gen-column-list"
      drawer-class="code-gen-column-setting-drawer"
      @confirm="handleColumnConfirm"
      @cancel="handleColumnCancel"
      @reset="handleColumnReset"
    />

    <selectDbTables
      ref="selectDbTablesRef"
      v-model="selectDbTablesIsOpen"
      :system="searchModel.system"
      @query="query"
    />

    <editCodeGen
      ref="editCodeGenRef"
      v-model="editCodeGenIsOpen"
      :system="searchModel.system"
      @query="query"
    />

    <codePreView ref="codePreViewRef" v-model="codePreViewIsOpen" />

    <!-- <selectDbTables
      ref="selectDbTablesRef"
      v-model="selectDbTablesIsOpen"
      :system="searchModel.system"
      @query="query"
    />
    <editCodeGen
      ref="editCodeGenRef"
      v-model="editCodeGenIsOpen"
      :system="searchModel.system"
      @query="query"
    />
     -->
  </el-container>
</template>

<script setup>
import { saveAs } from "file-saver";
import codePreView from "./components/codePreView.vue";
import editCodeGen from "./components/editCodeGen.vue";
import selectDbTables from "./components/selectDbTables.vue";
import { ref, computed, onMounted, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { FormDesign } from "vxe-design";

const { t } = useI18n();

const { proxy } = getCurrentInstance();

const showSearchHeader = ref(true);
const showColumnSetting = ref(false);

const btnLoading = ref(false);
const loading = ref(false);
// 初始化数据
const systemList = ref([]);
const tableColumns = ref([]);
const defaultTableColumns = ref([]);

// 初始化
const init = () => {
  // todo: 字典管理通用方法
  // systemList.value = proxy.$TOOL.dict.getList("SERVICE_MODEL");
  systemList.value = [
    {
      value: "zz-admin",
      label: "zz-admin",
    },
  ];

  // todo: 从数据库中查询表列，此处默认
  tableColumns.value = [
    {
      field: "tableName",
      title: "表名称",
      visible: true,
      fixed: "left", // null: 不固定, 'left': 左固定, 'right': 右固定
    },
    {
      field: "tableComment",
      title: "表描述",
      visible: true,
      fixed: null,
    },
    {
      field: "className",
      title: "实体",
      visible: true,
      fixed: null,
    },
    {
      field: "createDate",
      title: "创建时间",
      visible: true,
      fixed: null,
    },
    {
      field: "updateDate",
      title: "更新时间",
      visible: true,
      fixed: null,
    },
  ];
  defaultTableColumns.value = [
    {
      field: "tableName",
      title: "表名称",
      visible: true,
      fixed: "left", // null: 不固定, 'left': 左固定, 'right': 右固定
    },
    {
      field: "tableComment",
      title: "表描述",
      visible: true,
      fixed: null,
    },
    {
      field: "className",
      title: "实体",
      visible: true,
      fixed: null,
    },
    {
      field: "createDate",
      title: "创建时间",
      visible: true,
      fixed: null,
    },
    {
      field: "updateDate",
      title: "更新时间",
      visible: true,
      fixed: null,
    },
  ];
};

// 查询model
const searchModel = ref({
  system: "",
  tableName: "",
  tableComment: "",
  createDateRange: [],
});

const searchOptions = computed(() => {
  return {
    // 接收字段
    model: searchModel,
    // 配置表单
    column: [
      {
        label: "业务系统",
        type: "selectBase",
        field: "system",
        option: systemList.value,
      },
      {
        label: "表名称",
        type: "inputText",
        field: "tableName",
      },
      {
        label: "表描述",
        type: "inputText",
        field: "tableComment",
      },
      {
        label: "创建时间",
        type: "datePicker",
        field: "createDateRange",
        dateType: "daterange",
      },
    ],
  };
});

const getSearchData = (val) => {
  searchModel.value = val;
  query("search");
};

const resetFields = () => {};

const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const zzTableRef = ref();
// 查询
const query = async (mode) => {
  // 校验
  if (!searchModel.value.system) {
    ElMessage.warning("请选择业务系统");
    return;
  }

  loading.value = true;
  if (mode === "search") {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    };
  }
  let param = {
    ...searchModel.value,
  };

  try {
    let res = await proxy.$API.codeManagement.codeGen.queryWithPage.post(
      searchModel.value.system,
      param
    );
    if (res.code === "01") {
      tableData.value = res.bizList;
      tablePage.value.total = res.total;
      tablePage.value.pageSize = res.pageSize;
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage;
  searchModel.value.queryParam.pageSize = page.pageSize;
  query();
};

// 通过sql创建
const createBySql = () => {
  console.log("1");
};

const selectDbTablesRef = ref(null);
const selectDbTablesIsOpen = ref(false);
// 导入
const importByDB = () => {
  // 需要校验system
  if (!searchModel.value.system) {
    ElMessage.warning("请选择业务系统");
    return;
  }

  selectDbTablesIsOpen.value = true;
  selectDbTablesRef.value.title = "导入表";
};

// 生成
const batchGenCode = async () => {
  let arr = zzTableRef.value.getCheckboxRecords();
  // 校验
  if (arr.length === 0) {
    ElMessage.warning("请选择");
    return;
  }
  let ids = arr.map((e) => e.tableId);
  let res = await proxy.$API.codeManagement.codeGen.batchGenCode.post(
    searchModel.value.system,
    ids
  );
  openDownLoad(
    res,
    `生成代码-${proxy.$TOOL.format.formatDateTime(new Date())}.zip`
  );
};

const openDownLoad = async (ref, fileName) => {
  if (ref) {
    let lists = ref;
    var blob = new Blob([lists], { type: "application/octet-stream" });
    await saveAs(blob, fileName);
  }
};

// 批量删除
const batchDelete = () => {
  let arr = zzTableRef.value.getCheckboxRecords();
  // 校验
  if (arr.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  let ids = arr.map((e) => e.tableId);
  ElMessageBox.confirm("确定要删除吗？", "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // TODO: 替换为实际的API调用
      try {
        let res = await proxy.$API.codeManagement.codeGen.batchTureDelete.post(
          searchModel.value.system,
          ids
        );
        if (res.code === "01") {
          ElMessage.success("删除成功");
          query("search");
        } else {
          ElMessage.error("删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

const editCodeGenRef = ref(null);
const editCodeGenIsOpen = ref(false);
// 编辑
const toEdit = (row) => {
  editCodeGenIsOpen.value = true;
  editCodeGenRef.value.tableId = row.tableId;
};

// 表单设计
const formDesign = async (row) => {
  if (!row.tableId) {
    return;
  }

  let schemaId = ""
  // 调用api接口，通过tableId 查询schemaId
  try {
    let res = await proxy.$API.codeManagement.formSchema.queryByTableId.get(
      row.tableId
    );
    if (res.code === "01") {
      schemaId = res.data.schemaId;
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败");
    return;
  }
  
  proxy.$router.push({
    name: "FormDesigner",
    query: { schemaId: schemaId },
  });
};

// 预览
const codePreViewRef = ref(null);
const codePreViewIsOpen = ref(false);
const previewCode = async (row) => {
  if (!row.tableId) {
    return;
  }

  let res = await proxy.$API.codeManagement.codeGen.previewCode.get(
    searchModel.value.system,
    row.tableId
  );
  if (res.code == "01") {
    codePreViewRef.value.previewData = res.data;
    codePreViewIsOpen.value = true;
  }
};
// 生成代码
const genCode = async (row) => {
  let ids = [row.tableId];
  let res = await proxy.$API.codeManagement.codeGen.batchGenCode.post(
    searchModel.value.system,
    ids
  );
  openDownLoad(
    res,
    `生成代码-${proxy.$TOOL.format.formatDateTime(new Date())}.zip`
  );
};
// 同步
const synchDb = async (row) => {
  ElMessageBox.confirm("同步后无法恢复，请确认是否继续？", "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      // TODO: 替换为实际的API调用
      try {
        let res = await proxy.$API.codeManagement.codeGen.synchDb.get(
          searchModel.value.system,
          row.tableName,
          localStorage.getItem("language") || "zh-CN"
        );
        if (res.code === "01") {
          ElMessage.success("同步成功");
        } else {
          ElMessage.error("同步失败");
        }
      } catch (error) {
        console.error("同步失败:", error);
        ElMessage.error("同步失败");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消同步
    });
};
// 删除
const deleteRow = (row) => {
  let ids = [row.tableId];
  ElMessageBox.confirm("确定要删除吗？", "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // TODO: 替换为实际的API调用
      try {
        let res = await proxy.$API.codeManagement.codeGen.batchTureDelete.post(
          searchModel.value.system,
          ids
        );
        if (res.code === "01") {
          ElMessage.success("删除成功");
          query("search");
        } else {
          ElMessage.error("删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

const tabelSize = ref("small");

// 处理表格大小变化
const handleSizeChange = (size) => {
  tabelSize.value = size;
};

// 表列名
const tableColumnName = ref("code_gen_columns");

// 用于强制表格重新渲染的标记
const tableKey = ref(0);

// 中文标签页列设置事件处理
const handleColumnConfirm = (columns) => {
  // 使用深拷贝更新列设置，确保响应式更新
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  // 保存到本地存储
  localStorage.setItem(
    tableColumnName.value,
    JSON.stringify(tableColumns.value)
  );
  // 增加tableKey强制表格重新渲染
  tableKey.value += 1;
};

const handleColumnCancel = () => {
  // 加载保存的列设置
  loadColumnSettings();
  console.log("中文标签页列设置已取消");
};

const handleColumnReset = (columns) => {
  // 使用深拷贝更新列设置，确保响应式更新
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  // 保存到本地存储
  localStorage.setItem(
    tableColumnName.value,
    JSON.stringify(tableColumns.value)
  );
  // 增加tableKey强制表格重新渲染
  tableKey.value += 1;
  console.log("列设置已重置");
};

// 从本地存储加载列设置
const loadColumnSettings = () => {
  try {
    // 加载列设置
    const savedColumns = localStorage.getItem(tableColumnName.value);
    if (savedColumns) {
      const parsedColumns = JSON.parse(savedColumns);

      // 验证解析的数据是否为有效的数组
      if (Array.isArray(parsedColumns) && parsedColumns.length > 0) {
        // 验证每个列对象是否包含必要的属性
        const isValidColumns = parsedColumns.every(
          (col) =>
            col &&
            typeof col === "object" &&
            col.hasOwnProperty("field") &&
            col.hasOwnProperty("title")
        );

        if (isValidColumns) {
          tableColumns.value = parsedColumns;
          console.log("成功加载列设置");
        } else {
          console.warn("加载的列设置格式不正确，使用默认设置");
        }
      } else {
        console.warn("加载的列设置为空或格式错误，使用默认设置");
      }
    }

    // 增加tableKey强制表格重新渲染
    tableKey.value += 1;
  } catch (error) {
    console.error("加载列设置失败:", error);
  }
};

onMounted(() => {
  init();
  loadColumnSettings();
  // query('search')
});
</script>

<style lang="less" scoped></style>
